import app from 'flarum/forum/app';
import Modal from "flarum/common/components/Modal";
import ItemList from "flarum/common/utils/ItemList";
import Button from 'flarum/common/components/Button';
import Stream from 'flarum/utils/Stream';
import CaptchaModal from './CaptchaModal';

export default class ForgetFormModal extends Modal {
    // static isDismissible = true;
    static isDismissibleViaBackdropClick = false;

    oninit(vnode) {
        super.oninit(vnode);
        this.mobile = Stream('');
        this.count = Stream(60);
        this.code = Stream('');
        this.captcha = Stream('');
        this.password = Stream('');
        this.repassword = Stream('');
        this.sendingSms = false;
        this.liked = true;
        this.loading = false;
        this.captcha_url = '/captcha'
        this.issendcode = false;
    }
    className() {
        return 'password-modal-class';
    }
    title() {
        return m('p', '忘记密码');
    }
    content() {
        return m('.Modal-body', this.form().toArray());
    }
    form() {
        const items = new ItemList();
        items.add('mobile', m('.Form-group', [
            m('label', '手机号'),
            m('.auth-line',
                m("input.FormControl", {
                    name: "mobile",
                    type: "number",
                    placeholder: '请填写手机号',
                    bidi: this.mobile,
                }),
            )
        ]), 60);
        items.add(
            'captcha',
            m(".Form-group", m('.auth-line', [
                m("input.FormControl.msgcode", {
                    name: "captcha",
                    type: "text",
                    placeholder: '图形验证码',
                    bidi: this.captcha,
                }),
                m("img.captcha_img", {
                    src: this.captcha_url,
                    width: "120",
                    onclick: () => {
                        this.captcha_url = '/captcha?' + Math.random()
                        m.redraw();
                    }
                })
            ])),
            60
        )
        items.add('msgcode', m('.Form-group', [
            m('label', '验证码'),
            m('.auth-line', [
                m("input.FormControl.msgcode", {
                    name: "msgcode",
                    type: "number",
                    placeholder: '验证码',
                    bidi: this.code,
                }),
                m('button[type=button]', {
                    class: "Button Button--primary",
                    onclick: () => {
                        if (this.issendcode) {
                            return;
                        }
                        if (this.captcha() == '') {
                            app.alerts.show({ type: 'error' }, "请填写图形验证码！");
                            return;
                        }
                        if (this.mobile() == '') {
                            app.alerts.show({ type: 'error' }, "请填写手机号！");
                            return;
                        }
                        if (!this.isMobile(this.mobile())) {
                            app.alerts.show({ type: 'error' }, "手机号格式错误！");
                            return;
                        }
                        this.issendcode = true
                        app.request({
                            method: 'POST',
                            url: app.forum.attribute('apiUrl') + '/forgetsendcode',
                            body: {
                                mobile: this.mobile(),
                                captcha: this.captcha(),
                            },
                            errorHandler: this.onerror.bind(this),
                        }).then(() => {
                            app.alerts.show({ type: 'success' }, "短信发送成功");
                            this.countDown();
                            m.redraw();
                        }).catch(() => {
                            this.issendcode = false
                        }).then(this.loaded.bind(this));
                    }
                }, this.liked ? '获取验证码' : this.count() + '秒后重发')
            ])
        ]), 60)
        items.add(
            'password',
            <div className="Form-group" >
                <label>新密码 </label>
                < input
                    className="FormControl"
                    placeholder="请填写新密码"
                    type="password"
                    bidi={this.password}
                />
            </div>,
            60
        )
        items.add(
            'repassword',
            <div className="Form-group" >
                <label>确认新密码 </label>
                <input
                    className="FormControl"
                    placeholder="请填写新密码"
                    type="password"
                    bidi={this.repassword}
                />
            </div>,
            60
        )
        items.add(
            'submit',
            <div className="Form-group" >
                {
                    Button.component(
                        {
                            className: 'Button Button--primary',
                            type: 'submit',
                            loading: this.loading,
                        },
                        '立即修改'
                    )
                }
            </div>,
            - 10
        );
        return items;
    }
    countDown() {
        if (this.count() === 1) {
            this.count(60);
            this.liked = true;
            this.sendingSms = false;
        } else {
            this.count(this.count() - 1);
            this.liked = false;
            setTimeout(this.countDown.bind(this), 1000);
        }
        m.redraw();
    }
    onerror(error) {
        // console.log(error.response);
        error.alert.content = error.response;
        super.onerror(error);
        this.sendingSms = false;
        console.log('err');
    }
    isMobile(value) {
        return /^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value);
    }
    onsubmit(e) {
        e.preventDefault();
        this.loading = true;
        if (this.password() == "") {
            app.alerts.show({ type: 'error' }, "请输入密码！");
            return;
        }
        if (this.repassword() !== this.password()) {
            app.alerts.show({ type: 'error' }, "输入密码不一致！");
            return;
        }
        app.request({
            method: 'POST',
            url: app.forum.attribute('apiUrl') + '/forgetpwd',
            body: {
                mobile: this.mobile(),
                pwd: this.password(),
                code: this.code(),
            },
            errorHandler: this.onerror.bind(this),
        }).then(() => {
            app.modal.close()
            app.alerts.show({ type: 'success' }, "修改成功");
            m.redraw();
        }).catch(() => { })
            .then(this.loaded.bind(this));
    }
}
